package com.ygqh.baby.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.PromotionStatus;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.mapper.ActionMapper;
import com.ygqh.baby.po.Action;
import com.ygqh.baby.po.ActionExample;
import com.ygqh.baby.service.ActionService;

@Service
public class ActionServiceImpl implements ActionService {

	@Autowired
	private ActionMapper actionMapper;

	@Override
	public List<Action> find() {
		ActionExample example = new ActionExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return actionMapper.selectByExample(example);
	}

	@Override
	public int findCount() {
		ActionExample example = new ActionExample();
		example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
		return actionMapper.countByExample(example);
	}

	@Override
	public Action findById(Long id) {
		return actionMapper.selectByPrimaryKey(id);
	}

	@Override
	public int save(Action action) {
		return actionMapper.insertSelective(action);
	}

	@Override
	public int update(Action action) {
		return actionMapper.updateByPrimaryKeySelective(action);
	}

	@Override
	public ResultSet<Action> search(QueryInfo queryInfo, PromotionStatus pStatus, Date startDate, Date endDate, String q) {

		String state = pStatus == null ? null : pStatus.name();
		List<Action> list = actionMapper.selectSuper(queryInfo, state, startDate, endDate, q);
		int count = actionMapper.countSuper(state, startDate, endDate, q);
		ResultSet<Action> resultSet = new ResultSet<Action>(count, list);
		return resultSet;
	}

	@Override
	public int deleteSoft(Long[] ids) {
		Assert.notEmpty(ids);
		ActionExample example = new ActionExample();
		example.createCriteria().andIdIn(Arrays.asList(ids));
		Action record = new Action();
		record.setStatus(DataStatus.Delete);

		return actionMapper.updateByExampleSelective(record, example);
	}

	@Override
	public int deleteSoft(Long id) {
		return this.deleteSoft(new Long[] { id });
	}

	@Override
	public int saveOrUpdate(Action action) {
		int r = 0;
		if (action.getId() != null) {
			r = this.update(action);
		} else {
			r = this.save(action);
		}
		return r;
	}

}
